
import {  WeaFormItem, WeaLoadingGlobal,} from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import _ from 'lodash';
export declare interface MyWindow extends Window {
    cubeStore?: any;
    _xtable_CheckedCheckboxId: Function;
    _xtable_CleanCheckedCheckbox:Function;
    _table: {
        reLoad: Function,
    };
    CubeUtil?: any;
    AMap?: any;
    jsMind?: any;
    saveDragendMind?: Function;
    clickTable?: Function;
    modeopenFullWindowHaveBar: Function;
    weaHistory: any;
    openFullWindowBySelf: Function;
    openFullWindowHaveBar: Function;
    modeopenFullWindowHaveBarForWFList: Function;
    showFormModeMap: Function;
    openHrefWithChinese: Function;
    openHref: Function;
    WeaTools: any;
    handleQuickBtnClick?: Function;
    handleRightMenuClick?: Function;
    refreshTree?: Function;
    ModeMaxWidth?: number;
    proportion?: number;
    downloads?: Function;
    openUnFullWindow?: Function;
    __propertyChangeFnArray: any;

    checkCustomize: Function;
    startUploadAll: Function;
    reLoadModeTop: Function;
    pointerXY: Function;
    CardForm: any;
    changeLoadingState: Function;
    CubeTrigger: any;
    perfectHeight: () => number;
    __atdataready: boolean;
    __atdata: any;
    CK_REF: any;
    print: () => void;
    _cubeCard: {
        reLoad: Function,
        editCard: Function,
        delCard: Function
    };
    cubeOpenFullWindowBySelf:Function;
    modeForm:any;
    weaPortal?:any;
    cubeshowDdImg:Function;
    IMCarousel:any;
    __createDocFn:Function;
    ModeForm:any;
    showExportMenu:Function;
    ActiveXObject:any;
    antd:any;
    ecCom:any;
    comsMobx:any;
    React:any;
}
declare const window: MyWindow;


window.downloads = (files) => {
    window.open(`/weaver/weaver.file.FileDownload?fileid=${files}&download=1`);
}

export const changeViewType = (type: string) => {
    const { query } = window.weaHistory.getCurrentLocation();
    query.type = type;
    const queryStr = _.keys(_.mapKeys(query, (value, key) => {
        return `${key}=${value}`;
    })).join("&");
    window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
}
export const changeViewPage = (url: string, params: any) => {
    const { query } = window.weaHistory.getCurrentLocation();
    const queryStr = _.keys(_.mapKeys({ ...query, ...params }, (value, key) => {
        return `${key}=${value}`;
    })).join("&");
    window.location.href = `${url}?${queryStr}`;
}

export const replaceE8Url = (url: string) => {
    url = url.replace('/formmode/view/AddFormMode.jsp', '/spa/cube/index.html#/main/cube/card');
    url = url.replace('/formmode/view/AddFormModeIframe.jsp', '/spa/cube/index.html#/main/cube/card');
    url = url.replace('/formmode/search/CustomSearchBySimple.jsp', '/spa/cube/index.html#/main/cube/search');
    url = url.replace('/formmode/search/CustomSearchBySimpleIframe.jsp', '/spa/cube/index.html#/main/cube/search');
    url = url.replace('/formmode/tree/ViewCustomTree.jsp', '/spa/cube/index.html#/main/cube/tree');
    url = url.replace('/formmode/view/formModeComTab.jsp', '/spa/cube/index.html#/main/cube/reply');
    url = url.replace('/formmode/view/FormModeMap.jsp', '/spa/cube/index.html#/main/cube/map');
    if (url.indexOf("CustomSearchByAdvanced.jsp") > -1 || url.indexOf("CustomSearchByAdvancedIframe.jsp") > -1) {
        url = url.replace('/formmode/search/CustomSearchByAdvanced.jsp', '/spa/cube/index.html#/main/cube/search');
        url = url.replace('/formmode/search/CustomSearchByAdvancedIframe.jsp', '/spa/cube/index.html#/main/cube/search');
        url = `${url}&type=advanced`;
    }
    return url;
}

export const openHref = (url: string) => {
    window.open(replaceE8Url(url));
}
export const openHrefWithChinese = (url: string) => {
    openHref(dealChineseOfFieldParams(url));
}
window.openHrefWithChinese = openHrefWithChinese;
window.openHref = openHref;

export const modeopenFullWindowHaveBar = (url: string, _?: any) => {
    url = replaceE8Url(url)
    url = dealChineseOfFieldParams(url);
    url = url.replace(/\+/g, "%2B");
    openFullWindowHaveBar(url);
}
window.modeopenFullWindowHaveBar = modeopenFullWindowHaveBar;
export const dealChineseOfFieldParams = (url) => {
    if (url.indexOf("/workflow/request/AddRequest.jsp") == -1 && url.indexOf("/spa/cube/index.html#/main/cube/card") != 0) {
        return url;
    }
    var params = "";
    var path = url.substring(0, url.indexOf("?") + 1);
    var filedparams = url.substring(url.indexOf("?") + 1);
    var fieldparam = filedparams.split("&");
    for (var i = 0; i < fieldparam.length; i++) {
        var tmpindex = fieldparam[i].indexOf("=");
        if (tmpindex != -1) {
            var key = fieldparam[i].substring(0, tmpindex);
            var value = encodeURIComponent(fieldparam[i].substring(tmpindex + 1));
            params += "&" + key + "=" + value
        }
    }
    return path + params.substring(1);
}
export const modeopenFullWindowHaveBarForWFList = (url: string) => {
    openFullWindowHaveBarForWFList(url);
}
window.modeopenFullWindowHaveBarForWFList = modeopenFullWindowHaveBarForWFList;
function openFullWindowHaveBarForWFList(url) {
    var redirectUrl = url;
    var width = screen.availWidth - 10;
    var height = screen.availHeight - 50;
    var szFeatures = "top=0,";
    szFeatures += "left=0,";
    szFeatures += "width=" + width + ",";
    szFeatures += "height=" + height + ",";
    szFeatures += "directories=no,";
    szFeatures += "status=yes,toolbar=no,location=no,";
    szFeatures += "menubar=no,";
    szFeatures += "scrollbars=yes,";
    szFeatures += "resizable=yes"; //channelmode
    window.open(redirectUrl, "", szFeatures);
}
export const openFullWindowBySelf = (url) => {
    url = replaceE8Url(url)
    url = dealChineseOfFieldParams(url);
    url = url.replace(/\+/g, "%2B");
    window.location.href = url;
}
window.openFullWindowBySelf = openFullWindowBySelf;

export const cubeOpenFullWindowBySelf = (url) => {
    url = replaceE8Url(url)
    url = dealChineseOfFieldParams(url);
    url = url.replace(/\+/g, "%2B");
    if (url && url.indexOf('/spa/cube/index.html') === -1) { // 非建模路径，直接跳转相应路径
        window.location.replace(url);
    } else {
        let routeurl = url.split('#')[1];
        window.weaHistory.push({ pathname: routeurl });
    }
}
window.cubeOpenFullWindowBySelf = cubeOpenFullWindowBySelf;


export function openFullWindowHaveBar(url) {
    url = replaceE8Url(url)
    var redirectUrl = url;
    var width = screen.availWidth - 10;
    var height = screen.availHeight - 50;
    //if (height == 768 ) height -= 75 ;
    //if (height == 600 ) height -= 60 ;
    var szFeatures = "top=0,";
    szFeatures += "left=0,";
    szFeatures += "width=" + width + ",";
    szFeatures += "height=" + height + ",";
    szFeatures += "directories=no,";
    szFeatures += "status=yes,toolbar=no,location=no,";
    szFeatures += "menubar=no,";
    szFeatures += "scrollbars=yes,";
    szFeatures += "resizable=yes"; //channelmode
    window.open(redirectUrl, "", szFeatures);
}


//人力资源条件数据处理
export const spellResourceCondition = (datas) => {
    if (datas) {
        let value: string[] = [];
        datas.map((item) => {
            let candownload=item.canDownload=='是'?'1':'0';
            if (item.sharetype == "1") {
                value.push(`1_${item.relatedshare}_0_0_${candownload}`);
            } else if (item.sharetype == "2" || item.sharetype == "3") {
                value.push(`${item.sharetype}_${item.relatedshare}_0_${item.seclevel.replace('-', '|@|')}_${candownload}`);
            } else if (item.sharetype == "4") {
                value.push(`4_${item.relatedshare}_${item.rolelevel}_${item.seclevel.replace('-', '|@|')}_${candownload}`);
            } else if (item.sharetype == "5") {
                value.push(`5_0_0_${item.seclevel.replace('-', '|@|')}_${candownload}`);
            } else if (item.sharetype == "6") {
                if (item.joblevel == '2') {
                    value.push(`6_${item.relatedshare}_0_2|@|2_${candownload}`);
                } else {
                    value.push(`6_${item.relatedshare}_0_${item.joblevel}|@|${item.jobfield}_${candownload}`)
                }
            }
        });
        return value.join('~');
    }
    return '';
}


window.openFullWindowHaveBar = openFullWindowHaveBar;




export const addEnterFun = (searchFun)=> {
    let adEnterDiv = document.getElementsByClassName('cube-search-advance');
    if(adEnterDiv.length>0 && adEnterDiv[0]['onkeydown'] == null){
        adEnterDiv[0]['onkeydown'] = (e) => {
            if(e.keyCode == 13 && e.target.className.indexOf('ant-input')>-1){
                searchFun();
            }
        }
    }
}

// export const getBaseSearchs = (form, conditioninfo, customComponent?: any) => {
//     return getAdvancedSearchs(form, conditioninfo, customComponent)
// }
export const getCreateTemplateForm = (form, fields: any[]) => {
    const { isFormInit } = form;
    if (isFormInit) {
        let formParams = form.getFormParams(); // 获取表单的值
        const result = (<div>
            {fields[0].items.map(field => (
                <WeaFormItem
                    label={`${field.label}`
                    }
                    labelCol={{ span: field.labelcol }}
                    wrapperCol={{ span: field.fieldcol }}>
                    {/*根据 WeaSwitch 获取对应的组件*/}
                    <WeaSwitch fieldConfig={field} form={form} formParams={formParams} />
                    <div className="form-item-error" dangerouslySetInnerHTML={{ __html: form.$('templatename').$error }}></div>
                </WeaFormItem>))}
        </div>)
        return result;
    } else {
        return null;
    }
}
export const isUrl = (url): boolean => {
    var strRegex = '^((https|http|ftp|rtsp|mms)?://)'
        + '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' //ftp的user@
        + '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
        + '|' // 允许IP和DOMAIN（域名）
        + '([0-9a-z_!~*\'()-]+.)*' // 域名- www.
        + '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名
        + '[a-z]{2,6})' // first level domain- .com or .museum
        + '(:[0-9]{1,4})?' // 端口- :80
        + '((/?)|' // a slash isn't required if there is no file name
        + '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$';
    var re = new RegExp(strRegex);
    //re.test()
    if (re.test(url)) {
        return (true);
    } else {
        return (false);
    }
}

export class UrlSearch {
    constructor(location: Location) {
        const href = location.href;
        let num = href.indexOf("?");
        const str = href.substr(num + 1); //取得所有参数   stringvar.substr(start [, length ]
        const arr = str.split("&"); //各个参数放到数组里
        for (var i = 0; i < arr.length; i++) {
            num = arr[i].indexOf("=");
            if (num > 0) {
                this[arr[i].substring(0, num)] = arr[i].substr(num + 1);
            }
        }
    }
}

export function removeHTMLTag(str) {
    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str = str.replace(/&nbsp;/ig, '');//去掉&nbsp;
    str = str.replace(/&gt;/ig, ">");
    str = str.replace(/&lt;/ig, "<");
    str = str.replace(/&quot;/ig, "\"");
    return str;
}

export function getListKey(data: any): string {
    if ('randomFieldSubKeyd_id' in data) {
        return `${data.randomFieldId}_${data.randomFieldSubKeyd_id}`;
    } else {
        return `${data.randomFieldId}`;
    }
}
export function getListMainKey(data: any): string {
    return `${data.randomFieldId}`;
}
export function getListSubKey(data: any): string {
    if ('randomFieldSubKeyd_id' in data) {
        return `${data.randomFieldSubKeyd_id}`;
    } else {
        return '';
    }
}
export default window;


export const CardUtil = {
    findRowSpan: (row, col, ecMap) => {
        let find = false;
        for (let j = col; j >= 0 && !find; j--) {
            for (let i = row - 1; i >= 0 && !find; i--) {
                const cellObj = ecMap[i + "," + j];
                const rowSpan = cellObj ? (cellObj["rowspan"] || 1) : 0;
                const colSpan = cellObj ? (cellObj["colspan"] || 1) : 0;
                if (rowSpan > 1 && rowSpan >= (row - i + 1) && colSpan >= (col - j + 1)) {
                    find = true;
                }
            }
        }
        return find;
    }
}

export const convertSpecialChar = (str) => {
    str = str.toString();
    str = str.replace(/<br>/ig, "\n");
    str = str.replace(/&nbsp;/ig, " ");
    str = str.replace(/&lt;/ig, "<");
    str = str.replace(/&gt;/ig, ">");
    str = str.replace(/&quot;/ig, "\"");
    str = str.replace(/&amp;/ig, "&");
    return str;
}

//代码块中 控制全局spin
export const doGlobalSpin = (spinInfo) =>{
    try {
        const { isShow,size,tip } = spinInfo;
        if(isShow == 'show'){
            WeaLoadingGlobal.start({size:size,tip:tip});
        }else if(isShow == 'hide'){
            const timer = setTimeout(() => {
                WeaLoadingGlobal.end(); // 停止遮罩loading
                WeaLoadingGlobal.destroy(); // 销毁遮罩loading
                clearTimeout(timer);
            }, 500);
        }
    } catch (error) {
        console && console.log(error,'error')
    }
}
